#include <iostream>
#include <string>
#include <typeinfo>
#include <cassert>
#include <any>

class Any
{
private:
    class holder
    {
    public:
        virtual ~holder()
        {}
        virtual const std::type_info& type() = 0;
        virtual holder* clone() = 0;
    };
    template <class T>
    class placeholder : public holder
    {
    public:
        placeholder(const T& val): _val(val)
        {}
        /* 获取子类对象保存的数据类型 */
        virtual const std::type_info& type()
        {
            return typeid(T);
        }
        /* 针对当前子类对象，克隆出一个新的子类对象 */
        virtual holder* clone()
        {
            return new placeholder(_val);
        }
    public:
        T _val;
    };
public:
    Any(): _content(nullptr)
    {}
    template <class T>
    Any(const T& val): _content(new placeholder<T>(val))
    {
    }
    Any(const Any& other): _content(other._content ? other._content->clone() : nullptr)
    {}

    /* 获取子类对象保存的数据的指针 */
    template<class T>
    T* get()
    {
        // 想要获取的数据类型必须和保存的数据的类型一直！！
        assert(typeid(T) == _content->type());
        return &((placeholder<T>*)_content)->_val;// 待优化
    }

    template <class T>
    Any& operator=(const T& val)
    {
        Any(val).swap(*this);
        return *this;
    }
    Any& operator=(const Any& other)
    {
        Any(other).swap(*this);
        return *this;
    }

    Any& swap(Any& other)
    {
        std::swap(_content, other._content);
        return *this;
    }

    ~Any()
    {
        if(_content)
            delete _content;
    }
private:
    holder* _content;
};

class Test
{
public:
    Test()
    {
        std::cout << "Test()\n";
    }
    Test(const Test& t)
    {
        std::cout << "Test(const Test& t)\n";
    }
    ~Test()
    {
        std::cout << "~Test()\n";
    }
};

int main()
{
    // C++17
    std::any a;
    a = 10;
    int* pa = std::any_cast<int>(&a);
    std::cout << *pa << std::endl;

    a = std::string("hello");
    std::string* ps = std::any_cast<std::string>(&a);
    std::cout << *ps << std::endl;

    // Any a;
    // a = 10;
    // int* pa = a.get<int>();
    // std::cout << *pa << std::endl;

    // a = std::string("hello");
    // std::string* ps = a.get<std::string>();
    // std::cout << *ps << std::endl;

    // {
    //     Test t;
    //     a = t;
    // }

    return 0;
}